import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  Button,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
  message
} from 'antd'

import { Link } from 'react-router-dom'
import Channel from 'components/Channel'
import { ArticleStatus } from 'api/constants'

import { deleteArticle, getArticles } from 'api/article'
import defaultImg from 'assets/error.png'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleFilled
} from '@ant-design/icons'
const { confirm } = Modal

const { RangePicker } = DatePicker

export default class ArticleList extends Component {
  state = {
    articles: {}
  }
  // 因为这个reqParams变的时候不需要调用this.setState()，直接变了之后发请求就行。
  // 用于存放查询文章列表所有的参数
  reqParams = {
    page: 1,
    per_page: 10
  }
  columns = [
    {
      title: '封面',
      render({ cover }) {
        // console.log(cover)

        if (cover.type === 0) {
          // 无图渲染默认图片
          return (
            <img
              style={{ width: '200px', height: '120px', objectFit: 'cover' }}
              src={defaultImg}
              alt=""
            />
          )
        } else {
          // 有图，渲染第1张
          return (
            <img
              style={{ width: '200px', height: '120px', objectFit: 'cover' }}
              src={cover.images[0]}
            />
          )
        }
      }
    },
    {
      title: '标题',
      dataIndex: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = ArticleStatus.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    // {
    //   title: 'Tags',
    //   key: 'tags',
    //   dataIndex: 'tags',
    //   render: (_, { tags }) => (
    //     <>
    //       {tags.map((tag) => {
    //         let color = tag.length > 5 ? 'geekblue' : 'green'
    //         if (tag === 'loser') {
    //           color = 'volcano'
    //         }
    //         return (
    //           <Tag color={color} key={tag}>
    //             {tag.toUpperCase()}
    //           </Tag>
    //         )
    //       })}
    //     </>
    //   )
    // },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            shape="circle"
            type="primary"
            icon={<EditOutlined />}
            onClick={() => {
              this.handleEdit(record.id)
            }}
          ></Button>
          <Button
            shape="circle"
            type="primary"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              this.deleteArticle(record.id)
            }}
          ></Button>
          <a></a>
        </Space>
      )
    }
  ]

  componentDidMount() {
    this.getArticleList()
  }

  // 获取文章列表
  getArticleList = async () => {
    const { data } = await getArticles(this.reqParams)
    // console.log('articles is ', data)
    this.setState({
      articles: data
    })
  }
  // 删除文章记录
  deleteArticle = (id) => {
    console.log('删除：', id)
    // 弹窗确认
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleFilled />,
      content: '你确定要删除这篇文章吗？',
      onOk: async () => {
        const res = await deleteArticle(id)
        console.log(res)
        this.getArticleList()
        message.success('删除成功！')
      }
    })
  }
  // 校验成功后的回调
  onFinish = ({ status, channel_id, date }) => {
    console.log(channel_id)

    // console.log('values is ', values)
    if (status !== -1) {
      this.reqParams.status = status
    } else {
      delete this.reqParams.status
    }
    if (channel_id !== undefined) {
      this.reqParams.channel_id = channel_id
    } else {
      delete this.reqParams.channel_id
    }
    if (date) {
      this.reqParams.begin_pubdate = date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      this.reqParams.end_pubdate = date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete this.reqParams.begin_pubdate
      delete this.reqParams.end_pubdate
    }
    // 查询操作，需要重置页码为1
    this.reqParams.page = 1
    // console.log(Object.prototype.toString.call(date[0]))
    console.log(this.reqParams)
    this.getArticleList(this.reqParams)
  }
  // 改变分页参数
  changePagination = (page, pageSize) => {
    this.reqParams = { ...this.reqParams, page, per_page: pageSize }
    this.getArticleList(this.reqParams)
  }
  handleEdit = (id) => {
    this.props.history.push(`/home/publish/${id}`)
  }
  render() {
    const { total_count, results } = this.state.articles

    return (
      <div>
        <Card
          title={
            <Breadcrumb
              items={[
                {
                  title: <Link to="/home">首页</Link>
                },
                {
                  title: '文章列表'
                }
              ]}
            />
          }
        >
          <Form
            labelCol={{
              span: 0
            }}
            wrapperCol={{
              span: 16
            }}
            style={{
              maxWidth: 700
            }}
            initialValues={{
              status: -1
            }}
            onFinish={this.onFinish}
            // onFinishFailed={onFinishFailed}
            // autoComplete="off"
          >
            <Form.Item label="状态" name="status">
              <Radio.Group
              // onChange={onChange} value={value}
              >
                {ArticleStatus.map((item) => (
                  <Radio value={item.id} key={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>

            <Form.Item label="频道" name="channel_id">
              <Channel></Channel>
            </Form.Item>

            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 0,
                span: 16
              }}
            >
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`根据查询条件共查询到${total_count}条结果：`}>
          <Table
            columns={this.columns}
            dataSource={results}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              total: total_count,
              onChange: this.changePagination
            }}
          />
          ;
        </Card>
      </div>
    )
  }
}
